package org.example.aigc.controller;

import org.example.aigc.service.ModelService;
import org.example.aigc.utils.Reply;
import org.example.aigc.utils.WavHandle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.ExecutionException;

@RequestMapping("/model")
@RestController
public class ModelController {
    private final ModelService modelService;

    private final String audioUploadDir;

    @Autowired
    public ModelController(ModelService modelService, Environment environment) {
        this.modelService = modelService;
        this.audioUploadDir = Objects.requireNonNull(environment.getProperty("resources.audio-locations")).split(":", 2)[1];
        System.out.println("音频分片文件夹：" + audioUploadDir);
        if (audioUploadDir != null) {
            File file = new File(audioUploadDir);
            if (!file.exists()) {
                if (!file.mkdirs()) {
                    System.out.println("创建上传文件夹失败！");
                }
            }
        }
    }

    /**
     * 生成长音频
     *
     * @param referWav  参考音频
     * @param referText 参考文字
     * @param content   待生成的文字
     * @return 返回生成的文件名和信息
     * @throws IOException 文件读写错误
     */
    @PostMapping("/generateWav")
    public Reply generateWav(
            @RequestParam("referWav") String referWav,
            @RequestParam("referText") String referText,
            @RequestParam("content") String content) throws IOException, ExecutionException, InterruptedException {
        System.out.println(content);
        // 分割音频文件名
        List<String> wavName = new ArrayList<>();
        // 分割音频时间
        List<Double> wavTime = new ArrayList<>();
        double time = 0.0;

        // 设置参考的模型
        modelService.setModel(referWav, referText);

        // 将文件上传到服务器
        modelService.uploadFile(referWav, 1, 1);

        String fileName;
        List<String> contentList = List.of(content.split("\\|"));
        if (contentList.size() == 1) {
            fileName = modelService.getWav(contentList.get(0)).get();
            return Objects.requireNonNull(new Reply("获取音频文件").ok(0, "成功").put("fileName", fileName));
        }
        for (String s : contentList) {
            wavTime.add(time);
            fileName = modelService.getWav(s).get();
            wavName.add(fileName);
            wavName.add("blank_audio.wav");
            time += WavHandle.getWavLengthInSeconds(new File(audioUploadDir + fileName)) + 1;
        }
        wavTime.add(time);

        WavHandle wavHandle = new WavHandle();
        // 创建长音频
        for (String s : wavName) {
            wavHandle.addWavFile(Paths.get(audioUploadDir + s));
        }

        String newFileName = UUID.randomUUID() + "_new.wav";
        wavHandle.build(Paths.get(audioUploadDir + newFileName));
        for (String s : wavName) {
            if (!Objects.equals(s, "blank_audio.wav")) {
                File file = new File(audioUploadDir + s);
                boolean flag = file.delete();
                if (!flag) {
                    System.out.println("删除文件 " + s + "失败");
                }
            }
        }
        return Objects.requireNonNull(new Reply("获取音频文件").ok(0, "成功").put("fileName", newFileName)).put("time", wavTime);
    }

    /**
     * 生成长视频
     *
     * @param appearanceName 虚拟形象的视频文件名
     * @param wavName        长音频的文件名
     * @return 返回生成的长视频文件名
     * @throws IOException 文件读写错误
     */
    @PostMapping("/generateMP4")
    public Reply generateMP4(
            @RequestParam("appearanceName") String appearanceName,
            @RequestParam("wavName") String wavName
    ) throws IOException {
        modelService.uploadFile(appearanceName, 0, 0);
        modelService.uploadFile(wavName, 1, 0);
        String fileName = modelService.getMP4(appearanceName, wavName);
        return new Reply("生成长视频").ok(0, "成功").put("fileName", fileName);
    }
}
